<?php

namespace app\modules\backend\controllers;

use app\models\User;
use app\models\UserAssignable;
use Yii;
use app\models\UserLog;
use app\models\searchs\UserLogSearch;
use yii\rbac\Item;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * UserLogController implements the CRUD actions for UserLog model.
 */
class UserLogController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all UserLog models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new UserLogSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single UserLog model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new UserLog model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new UserLog();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing UserLog model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing UserLog model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    public function actionRefuse($id)
    {
        $model = $this->findModel($id);
        $model->status = 2;

        if($model->update()){
            $this->refuseMail($model->person->email);
            return $this->redirect(['index']);
        }else{
            return $this->redirect(['view','id'=>$model->id]);
        }
    }

    public function actionAssign($id){

        $model = $this->findModel($id);
        if($model->person->is_assigned){
            return $this->redirect(['index']);
        }
        $user = User::findOne(['username'=>$model->company->code]);
        if($user){
     //       $user->setPassword($model->psw_tmp);
     //       $user->save();
        }else{
            $user = new User();
            $user->username = $model->company->code;
            $user->setPassword($model->psw_tmp);
            $user->generateAuthKey();
            $user->save();
        }
        return $this->render('role_assign',['model'=>$model]);
    }

    public function actionGetroles($id){
        $authManager = \Yii::$app->authManager;
        $roles = array_keys($authManager->getRoles());
        $userLog = $this->findModel($id);
        $user = User::findOne(['username'=>$userLog->company->code]);
        $assginedObjs = UserAssignable::findAll(['user_id'=>$user->id]);
        $assigned = array();
        foreach($assginedObjs as $a){
            $assigned[] = $a->role_name;
        }
        $available = array();
        foreach($roles as $role){
            if(in_array($role,$assigned)){
                continue;
            }
            $available[] = $role;
        }
        $roles = [];
        $roles['available'] = $available;
        $roles['assigned'] = $assigned;
        return json_encode($roles);
    }

    public function actionPass($id,$assign_num,$assigned){
        $assigned = explode(",",$assigned);
        $userLog = $this->findModel($id);
        $user = User::findOne(['username'=>$userLog->company->code]);
        if($user){
            $user->assign_num = $assign_num;
            $user->person_id = $userLog->person_id;
            $user->setPassword($userLog->psw_tmp);
            if(!$user->save()){
                return $this->redirect('index.php?r=/site/error');
            }
        }else{
            return $this->redirect('index.php?r=/site/error');
        }
        $assigned_orign = array();
        $assginedObjs = UserAssignable::findAll(['user_id'=>$user->id]);
        foreach($assginedObjs as $a){
            $assigned_orign[] = $a->role_name;
        }
        $delete = array();
        foreach($assigned_orign as $a){
            if(in_array($a,$assigned)){
                continue;
            }
            $delete[] = $a;
        }
        $add = array();
        foreach($assigned as $a){
            if(in_array($a,$assigned_orign)){
                continue;
            }
            $add[] = $a;
        }
        UserAssignable::deleteAll(['role_name'=>$delete]);
        foreach($add as $item=>$name){
            $temp = new UserAssignable();
            $temp->role_name = $name;
            $temp->user_id = $user->id;
            $temp->save();
        }
        $userLog->status=3;
        $userLog->save();
        $username = $userLog->company->code;
        $password = $userLog->psw_tmp;
        $address = $userLog->person->email;

        $person = $userLog->person;
        $authManger = \Yii::$app->authManager;
        if($userLog->type=1) {
            $authManger->assign($authManger->getRole('公司负责人'), $user->id);
        }else{
            $authManger->assign($authManger->getRole('园区负责人'), $user->id);
        }
        $person->is_assigned = 1;
        $person->update();
        if(!$this->successMail($username,$password,$address)){
            return $this->redirect('index.php?r=/site/error');
        }
        return $this->redirect(['index']);

    }

    public function successMail($username,$password,$address){
        return Yii::$app->mailer->compose()
    //        ->setFrom('zhoujc1104@163.com')
            ->setTo($address)
            ->setSubject('邦伯农业:您的账号申请成功')
            ->setHtmlBody('
                <style>
                    table{
                        marign:0 auto;
                    }
                    table td{
                        width:200px;
                    }
                    table{
                        border: 1px solid #000000;
                    }
                    th{
                        background-color: #CCCCCC;
                    }
                </style>
                <h3>您的账号审核已通过请妥善保管好您的密码:</h3>
                <table style="border:1px solid #000;margin:0 auto;">
                    <tr><th>用户名</th><td>'.$username.'</td></tr>
                    <tr><th>密码</th><td>'.$password.'</td></tr>
                </table>')
            ->send();
    }

    public function refuseMail($address){
        return Yii::$app->mailer->compose()
            //        ->setFrom('zhoujc1104@163.com')
            ->setTo($address)
            ->setSubject('邦伯农业:您的账号申请失败')
            ->setHtmlBody('
                <p>尊敬的用户：</p>
                <p style="text-indent:2em;">很抱歉的通知您，您的账号申请已经被管理员拒绝。请确认您提交的信息准确，
                如有异议，可联系客服021-56385780 &nbsp; 021-56552073</p>')
            ->send();

    }


    /**
     * Finds the UserLog model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return UserLog the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = UserLog::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    function generate_password( $length = 8 ) {
        // 密码字符集，可任意添加你需要的字符
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';

        $password = '';
        for ( $i = 0; $i < $length; $i++ )
        {
            // 这里提供两种字符获取方式
            // 第一种是使用 substr 截取$chars中的任意一位字符；
            // 第二种是取字符数组 $chars 的任意元素
            // $password .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
            $password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
        }

        return $password;
    }


}
